package chat.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.BlockingQueue;

import chat.user.Message;
import chat.user.Request;
import chat.user.User;

public class MultiThread {

	private static Queue<Request> InQueue = new LinkedList<Request>();
	private static List<Socket> socket_list = new ArrayList<Socket>();
	private static List<User> user_list = new ArrayList<User>();
	private static Map<String, ServerThread> client_list = new HashMap<String, ServerThread>();

	public MultiThread() throws IOException {

		ServerSocket server = null;

		new Thread(new SocketWriter()).start();

		new Thread(new SocketProcessor()).start();

		GroupProcessor groupProcessor = new GroupProcessor();

		try {

			server = new ServerSocket(4444);

		} catch (IOException e) {

			System.out.println("Cannot create server on 4444 port");
		}

		try {

			while (true) {

				Socket socket = server.accept();

				System.out.println("Client connected");

				new ServerThread(socket);
				
			}
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	public static boolean RemoveFromInQueue(Object r) {

		return InQueue.remove(r);

	}

	public static boolean addInMessage(Request r) {

		return InQueue.add(r);

	}

	public static boolean addUser(User u) {

		return user_list.add(u);

	}

	public static Object getInMessage() {

		return InQueue.peek();

	}

	public static boolean RemoveFromInQueue(Socket s) {

		return socket_list.remove(s);

	}

	public static boolean addInSocket(Socket s) {

		return socket_list.add(s);

	}

	public static Socket getSocket(int number) {

		return socket_list.get(number);

	}

	public static int getCountInQueue() {

		return InQueue.size();
	}

	public static int getCountSocketQueue() {

		return socket_list.size();
	}

	public static void addClient(String user_name, ServerThread client) {

		client_list.put(user_name, client);

	}

	public static void main(String[] args) {

		try {
			new MultiThread();
		} catch (IOException e) {
			e.printStackTrace();

		}
	}
	
	/*public static synchronized void disconnectThread(ServerThread thread, Socket socket, ObjectInputStream ois){
		try{
			thread.interrupt();
			socket.shutdownInput();
			socket.shutdownOutput();
			ois.close();
			//socket.close();
		}
		catch (Exception e){
			e.printStackTrace();
		}
	}*/

}
